<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Example: CSV - A thoughtful introduction to the pest parser</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="An introduction to the pest parser by implementing a Rust grammar subset">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="shortcut icon" href="../favicon.png">
        <link rel="stylesheet" href="../css/variables.css">
        <link rel="stylesheet" href="../css/general.css">
        <link rel="stylesheet" href="../css/chrome.css">
        <link rel="stylesheet" href="../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../highlight.css">
        <link rel="stylesheet" href="../tomorrow-night.css">
        <link rel="stylesheet" href="../ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        
    </head>
    <body class="light">
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../";
            var default_theme = "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = default_theme; }
            document.body.className = theme;
            document.querySelector('html').className = theme + ' js';
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li><a href="../intro.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li><ol class="section"><li><a href="../examples/csv.html" class="active"><strong aria-hidden="true">1.1.</strong> Example: CSV</a></li></ol></li><li><a href="../parser_api.html"><strong aria-hidden="true">2.</strong> Parser API</a></li><li><ol class="section"><li><a href="../examples/ini.html"><strong aria-hidden="true">2.1.</strong> Example: INI</a></li></ol></li><li><a href="../grammars/grammars.html"><strong aria-hidden="true">3.</strong> Grammars</a></li><li><ol class="section"><li><a href="../grammars/peg.html"><strong aria-hidden="true">3.1.</strong> Parsing expression grammars</a></li><li><a href="../grammars/syntax.html"><strong aria-hidden="true">3.2.</strong> Syntax of pest parsers</a></li><li><a href="../grammars/built-ins.html"><strong aria-hidden="true">3.3.</strong> Built-in rules</a></li><li><a href="../examples/json.html"><strong aria-hidden="true">3.4.</strong> Example: JSON</a></li><li><a href="../examples/jlang.html"><strong aria-hidden="true">3.5.</strong> Example: The J language</a></li></ol></li><li><a href="../precedence.html"><strong aria-hidden="true">4.</strong> Operator precedence (WIP)</a></li><li><ol class="section"><li><a href="../examples/calculator.html"><strong aria-hidden="true">4.1.</strong> Example: Calculator (WIP)</a></li></ol></li><li><a href="../examples/awk.html"><strong aria-hidden="true">5.</strong> Final project: Awk clone (WIP)</a></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                                <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                            </ul>
                            
                            <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                                <i class="fa fa-search"></i>
                            </button>
                            
                        </div>

                        <h1 class="menu-title">A thoughtful introduction to the pest parser</h1> 

                        <div class="right-buttons">
                            <a href="../print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                            
                        </div>
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <a class="header" href="#example-csv" id="example-csv"><h1>Example: CSV</h1></a>
<p>Comma-Separated Values is a very simple text format. CSV files consist of a
list of <em>records</em>, each on a separate line. Each record is a list of <em>fields</em>
separated by commas.</p>
<p>For example, here is a CSV file with numeric fields:</p>
<pre><code>65279,1179403647,1463895090
3.1415927,2.7182817,1.618034
-40,-273.15
13,42
65537
</code></pre>
<p>Let's write a program that computes the <strong>sum of these fields</strong> and counts the
<strong>number of records</strong>.</p>
<a class="header" href="#setup" id="setup"><h2>Setup</h2></a>
<p>Start by initializing a new project using <a href="https://doc.rust-lang.org/cargo/">Cargo</a>:</p>
<pre><code class="language-shell">$ cargo init --bin csv-tool
     Created binary (application) project
$ cd csv-tool
</code></pre>
<p>Add the <code>pest</code> and <code>pest_derive</code> crates to the dependencies section in <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[dependencies]
pest = &quot;2.0&quot;
pest_derive = &quot;2.0&quot;
</code></pre>
<p>And finally bring <code>pest</code> and <code>pest_derive</code> into scope in <code>src/main.rs</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate pest;
#[macro_use]
extern crate pest_derive;
#}</code></pre></pre>
<p>The <code>#[macro_use]</code> attribute is necessary to use <code>pest</code> to generate parsing
code! This is a very important attribute.</p>
<a class="header" href="#writing-the-parser" id="writing-the-parser"><h2>Writing the parser</h2></a>
<p><code>pest</code> works by compiling a description of a file format, called a <em>grammar</em>,
into Rust code. Let's write a grammar for a CSV file that contains numbers.
Create a new file named <code>src/csv.pest</code> with a single line:</p>
<pre><code class="language-pest">field = { (ASCII_DIGIT | &quot;.&quot; | &quot;-&quot;)+ }
</code></pre>
<p>This is a description of every number field: each character is either an ASCII
digit <code>0</code> through <code>9</code>, a full stop <code>.</code>, or a hyphen–minus <code>-</code>. The plus
sign <code>+</code> indicates that the pattern can occur one or more times.</p>
<p>Rust needs to know to compile this file using <code>pest</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use pest::Parser;

#[derive(Parser)]
#[grammar = &quot;csv.pest&quot;]
pub struct CSVParser;
#}</code></pre></pre>
<p>If you run <code>cargo doc</code>, you will see that <code>pest</code> has created the function
<code>CSVParser::parse</code> and an enum called <code>Rule</code> with a single variant
<code>Rule::field</code>.</p>
<p>Let's test it out! Rewrite <code>main</code>:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    let successful_parse = CSVParser::parse(Rule::field, &quot;-273.15&quot;);
    println!(&quot;{:?}&quot;, successful_parse);

    let unsuccessful_parse = CSVParser::parse(Rule::field, &quot;this is not a number&quot;);
    println!(&quot;{:?}&quot;, unsuccessful_parse);
}
</code></pre></pre>
<pre><code class="language-shell">$ cargo run
  [ ... ]
Ok([Pair { rule: field, span: Span { str: &quot;-273.15&quot;, start: 0, end: 7 }, inner: [] }])
Err(Error { variant: ParsingError { positives: [field], negatives: [] }, location: Pos(0), path: None, line: &quot;this is not a number&quot;, continued_line: None, start: (1, 1), end: None })
</code></pre>
<p>Yikes! That's a complicated type! But you can see that the successful parse was
<code>Ok</code>, while the failed parse was <code>Err</code>. We'll get into the details later.</p>
<p>For now, let's complete the grammar:</p>
<pre><code class="language-pest">field = { (ASCII_DIGIT | &quot;.&quot; | &quot;-&quot;)+ }
record = { field ~ (&quot;,&quot; ~ field)* }
file = { SOI ~ (record ~ (&quot;\r\n&quot; | &quot;\n&quot;))* ~ EOI }
</code></pre>
<p>The tilde <code>~</code> means &quot;and then&quot;, so that <code>&quot;abc&quot; ~ &quot;def&quot;</code> matches <code>abc</code> followed
by <code>def</code>. (For this grammar, <code>&quot;abc&quot; ~ &quot;def&quot;</code> is exactly the same as <code>&quot;abcdef&quot;</code>,
although this is not true in general; see <a href="../grammars/syntax.html">a later chapter about
<code>WHITESPACE</code></a>.)</p>
<p>In addition to literal strings (<code>&quot;\r\n&quot;</code>) and built-ins (<code>ASCII_DIGIT</code>), rules
can contain other rules. For instance, a <code>record</code> is a <code>field</code>, and optionally
a comma <code>,</code> and then another <code>field</code> repeated as many times as necessary. The
asterisk <code>*</code> is just like the plus sign <code>+</code>, except the pattern is optional: it
can occur any number of times at all (zero or more).</p>
<p>There are two more rules that we haven't defined: <code>SOI</code> and <code>EOI</code> are two
special rules that match, respectively, the <em>start of input</em> and the <em>end of
input</em>. Without <code>EOI</code>, the <code>file</code> rule would gladly parse an invalid file! It
would just stop as soon as it found the first invalid character and report a
successful parse, possibly consisting of nothing at all!</p>
<a class="header" href="#the-main-program-loop" id="the-main-program-loop"><h2>The main program loop</h2></a>
<p>Now we're ready to finish the program. We will use <a href="https://doc.rust-lang.org/std/fs/struct.File.html"><code>File</code></a> to read the CSV
file into memory. We'll also be messy and use <a href="https://doc.rust-lang.org/std/option/enum.Option.html#method.expect"><code>expect</code></a> everywhere.</p>
<pre><pre class="playpen"><code class="language-rust">use std::fs;

fn main() {
    let unparsed_file = fs::read_to_string(&quot;numbers.csv&quot;).expect(&quot;cannot read file&quot;);

    // ...
}
</code></pre></pre>
<p>Next we invoke the parser on the file. Don't worry about the specific types for
now. Just know that we're producing a <a href="https://docs.rs/pest/2.0/pest/iterators/struct.Pair.html"><code>pest::iterators::Pair</code></a> that represents
the <code>file</code> rule in our grammar.</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    // ...

    let file = CSVParser::parse(Rule::file, &amp;unparsed_file)
        .expect(&quot;unsuccessful parse&quot;) // unwrap the parse result
        .next().unwrap(); // get and unwrap the `file` rule; never fails

    // ...
}
</code></pre></pre>
<p>Finally, we iterate over the <code>record</code>s and <code>field</code>s, while keeping track of the
count and sum, then print those numbers out.</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    // ...

    let mut field_sum: f64 = 0.0;
    let mut record_count: u64 = 0;

    for record in file.into_inner() {
        match record.as_rule() {
            Rule::record =&gt; {
                record_count += 1;

                for field in record.into_inner() {
                    field_sum += field.as_str().parse::&lt;f64&gt;().unwrap();
                }
            }
            Rule::EOI =&gt; (),
            _ =&gt; unreachable!(),
        }
    }

    println!(&quot;Sum of fields: {}&quot;, field_sum);
    println!(&quot;Number of records: {}&quot;, record_count);
}
</code></pre></pre>
<p>If <code>p</code> is a parse result (a <a href="https://docs.rs/pest/2.0/pest/iterators/struct.Pair.html"><code>Pair</code></a>) for a rule in the grammar, then
<code>p.into_inner()</code> returns an <a href="https://doc.rust-lang.org/std/iter/index.html">iterator</a> over the named sub-rules of that rule.
For instance, since the <code>file</code> rule in our grammar has <code>record</code> as a sub-rule,
<code>file.into_inner()</code> returns an iterator over each parsed <code>record</code>. Similarly,
since a <code>record</code> contains <code>field</code> sub-rules, <code>record.into_inner()</code> returns an
iterator over each parsed <code>field</code>.</p>
<a class="header" href="#done" id="done"><h2>Done</h2></a>
<p>Try it out! Copy the sample CSV at the top of this chapter into a file called
<code>numbers.csv</code>, then run the program! You should see something like this:</p>
<pre><code class="language-shell">$ cargo run
  [ ... ]
Sum of fields: 2643429302.327908
Number of records: 5
</code></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="../intro.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="../parser_api.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a href="../intro.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="../parser_api.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>

        

        

        

        
        <script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        
        <script type="text/javascript" src="../highlight-pest.js"></script>
        

        

    </body>
</html>
